package com.ruoyi.chatAi.utils;

import com.ruoyi.chatAi.domain.ChatMessage;
import com.ruoyi.chatAi.service.ChatMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
@Slf4j
public class UserChatMemory implements ChatMemory
{

    @Autowired
    private ChatMessageService chatMessageService;

    private final List<Message> memory;

    @Override
    public void add(String conversationId, List<Message> messages) {

    }


    @Override
    public List<Message> get(String conversationId, int lastN) {
        if (conversationId == null) {
            return Collections.emptyList();
        }

        try {
            // 查询数据库中的消息
            List<ChatMessage> chatMessages = chatMessageService.selectChatMessagesBySessionId(conversationId);

            if (chatMessages == null || chatMessages.isEmpty()) {
                return Collections.emptyList();
            }

            // 将ChatMessage转换为Spring AI消息
            List<Message> messages = chatMessages.stream()
                    .map(this::convertToAiMessage)
                    .collect(Collectors.toList());

            // 限制返回最近的N条消息
            if (messages.size() > lastN) {
                return messages.subList(messages.size() - lastN, messages.size());
            }
            log.info("打印数据");
            for (Message message : messages) {
                log.info(message.getText());
            }
            return messages;
        } catch (Exception e) {
            log.error("从数据库获取会话消息失败: " + conversationId, e);
            return Collections.emptyList();
        }
    }

    @Override
    public void clear(String conversationId) {

    }


    /**
     * 将ChatMessage转换为Spring AI消息
     */
    private Message convertToAiMessage(ChatMessage chatMessage) {
        if (chatMessage == null || chatMessage.getContent() == null) {
            return null;
        }

        return switch (chatMessage.getRole()) {
            case "user" -> new UserMessage(chatMessage.getContent());
            case "assistant" -> new AssistantMessage(chatMessage.getContent());
            case "system" -> new SystemMessage(chatMessage.getContent());
            default -> new UserMessage(chatMessage.getContent()); // 默认作为用户消息
        };
    }
}
